package com.tanhua.dubbo.utils;

import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class TimeLineService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Async  //注解写在方法上后，该方法就会实现新线程异步处理时间线动态的保存
    public  void saveTimeLine(Movement movement) {
        //模拟保存数据较慢，实现异步处理请求
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //查询当前用户的好友
        Long userId = movement.getUserId();
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria);
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        //todo 排除不可见的用户，记录关系表数据（之后做）,目前先构建默认
        for (Friend friend : friends) {
            MovementTimeLine line = new MovementTimeLine();
            line.setUserId(userId);
            line.setMovementId(movement.getId());
            line.setFriendId(friend.getFriendId());
            line.setCreated(System.currentTimeMillis());
            mongoTemplate.save(line);
        }
    }
}
